export type GlobalConfig = {
  configKey: string;
  configValue: string;
  extraInfo: string;
  paramsJson: string;
};

type Script = {
  id: number;
  name: string;
  content: string;
  description: string;
};

export type SiteConfig = {
  id: number;
  scripts: Script[];
  websiteCode: string;
  websiteDesc: string;
  websiteImgUrl: string;
  websiteName: string;
  websiteType: string;
  websiteUrl: string;
};

export const useConfig = defineStore('config', {
  state: () => ({
    init: false,
    cfgs: [] as GlobalConfig[],
    /**
     * 站点信息
     */
    siteConfigs: [] as SiteConfig[],
  }),
  actions: {
    async getConfigByKey(key: string) {
      if (!this.cfgs.length) {
        const res = await get<GlobalConfig[]>(Prefix.api + '/globals/default');
        if (res.code == 'ok') {
          this.cfgs = res.data;
        }
      }
      return this.cfgs.find(item => item.configKey == key);
    },
    async getSiteConfigs() {
      if (!this.siteConfigs.length) {
        const res = await get<SiteConfig[]>(Prefix.api + '/script/list');
        if (res.code == 'ok') {
          this.siteConfigs = res.data;
        }
      }
      return this.siteConfigs;
    },
    async getSiteConfig(website_code: string, description: string) {
      const configs = await this.getSiteConfigs();
      const website = configs.find(item => item.websiteCode == website_code);
      return website?.scripts.find(item => item.description == description)?.id;
    },
  },
});
